<template>
<!-- 路由页面 -->
<div class="message-box-shadow message-content__wrapper">
    <!-- 侧栏 -->         
    <div class="_Sidebar_1k2p2_10" >
      <div class="_SidebarHeader_1k2p2_17">
        <div class="_SidebarTitle_1k2p2_28">最近消息</div>
      </div> 
      <div class="scroll-container">
        <el-scrollbar  style="height: 100%;">
          <div class="_SessionItem_dnmx0_1" 
          v-for="item in personList" 
          :key="item.userId"
          :class="{ '_SessionItemIsActive_dnmx0_12': item.userId === currentChatPerson?.userId}" 
          @click="enterChat(item)">
            <div class="_SessionItem__Avatar_dnmx0_21">
              <el-avatar  :size="41" :src="item.avatar"></el-avatar>
              <div class="bili-avatar__layer" style="left: 34.5px; top: 34.5px; width: 14px; height: 14px; opacity: 1; background-color: transparent; border-radius: 50%; box-sizing: border-box;">
                <div class="bili-avatar__layer__res local-4">
                </div>
              </div>
            <div class="_SessionItem__Main_dnmx0_42">
            <div class="_SessionItem__Title_dnmx0_49">
              <div class="_SessionItem__Name_dnmx0_67">{{ item.nickName }}</div>
            </div>
          <div class="_SessionItem__Info_dnmx0_97">
          <div class="_SessionItem__Message_dnmx0_107">{{ item.lastMessage }}</div>
          </div>
          </div>
          <div class="_SessionItem__Notification_dnmx0_114" v-show="item.unreadCount > 0">
            <div class="_SessionItem__NotificationNumber_dnmx0_124">{{ item.unreadCount }}</div>
          </div>
        </div>
       </div>
      </el-scrollbar>
      </div>      
    </div>
    <div class="_Main_1k2p2_60" v-if="!chatContentEl">
        <div class="_ChatWindow_1lacc_1 _ChatWindowIsActive_1lacc_11">
          <div class="_ChatPlaceholder_1lacc_95">
            <img src="https://s1.hdslb.com/bfs/seed/jinkela/short/message/img/gochat.png">
            <p>快去登录吧 ( ゜- ゜)つロ</p>
          </div>
        </div>
      </div> 
     <!--聊天框  -->
     <div class="_Main_1k2p2_60"   v-if="chatContentEl">
        <div class="_ChatHeader_1lacc_14">
          <div class="_ContactName_1lacc_26">{{ currentChatPerson.nickName }}</div>
          <div class="_ContactSettings_1lacc_30">
            <div data-action="more" class="_MoreAction_1lacc_39">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M13.7485 5.49841C13.7485 6.46404 12.9657 7.24683 12.0001 7.24683C11.0344 7.24683 10.2516 6.46404 10.2516 5.49841C10.2516 4.53279 11.0344 3.75 12.0001 3.75C12.9657 3.75 13.7485 4.53279 13.7485 5.49841ZM13.7484 18.4982C13.7484 19.4639 12.9656 20.2467 11.9999 20.2467C11.0343 20.2467 10.2515 19.4639 10.2515 18.4982C10.2515 17.5326 11.0343 16.7498 11.9999 16.7498C12.9656 16.7498 13.7484 17.5326 13.7484 18.4982ZM11.9999 13.7487C12.9656 13.7487 13.7484 12.9658 13.7484 12.0002C13.7484 11.0345 12.9656 10.2517 11.9999 10.2517C11.0343 10.2517 10.2515 11.0345 10.2515 12.0002C10.2515 12.9658 11.0343 13.7487 11.9999 13.7487Z" fill="currentColor"></path></svg>
            </div>
          </div>
        </div>
      <!--聊天对话框--> 
      <div class="_ChatContent_1lacc_58">
        <el-scrollbar class="_InfiniteScroll_wmrzv_1 im-scroll" ref="chatScrollbar" height="100%">
          <template v-for="(msg, index) in messageList" :key="msg.id">
            <div v-if="shouldShowTime(index)" class="time-divider"><span class="label">{{ handleTime(msg.sendTime) }}</span></div>
            <!-- 设置双方消息样式 -->
            <div :class="['chat-message', msg.senderId === userInfo.userId ? 'from-me' : 'from-them']">
              <el-avatar
                v-if="msg.senderId !== userInfo.userId"
                :size="32"
                :src="currentChatPerson?.avatar"
                class="avatar"
              />
              <div class="bubble">
                <div class="content">{{ msg.content }}</div>
              </div>
              <el-avatar
                v-if="msg.senderId === userInfo.userId"
                :size="32"
                :src="userInfo.avatar"
                class="avatar"
              />
            </div>
          </template>
        </el-scrollbar>
      </div>
      <!-- 发送消息框 -->
      <div class="_ChatFooter_1lacc_89">
        <div class="_MessageSendBox__Toolbar_1izxa_6">
          <input ref="uploaderPic" type="file" accept="image/*" style="display:none"/>
          <div class="_MessageSendBox__ToolBtn_1izxa_13" @click="handleChooseImage">
            <svg t="1755065686548" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6391" width="24" height="24"><path d="M938.666667 553.92V768c0 64.8-52.533333 117.333333-117.333334 117.333333H202.666667c-64.8 0-117.333333-52.533333-117.333334-117.333333V256c0-64.8 52.533333-117.333333 117.333334-117.333333h618.666666c64.8 0 117.333333 52.533333 117.333334 117.333333v297.92z m-64-74.624V256a53.333333 53.333333 0 0 0-53.333334-53.333333H202.666667a53.333333 53.333333 0 0 0-53.333334 53.333333v344.48A290.090667 290.090667 0 0 1 192 597.333333a286.88 286.88 0 0 1 183.296 65.845334C427.029333 528.384 556.906667 437.333333 704 437.333333c65.706667 0 126.997333 16.778667 170.666667 41.962667z m0 82.24c-5.333333-8.32-21.130667-21.653333-43.648-32.917333C796.768 511.488 753.045333 501.333333 704 501.333333c-121.770667 0-229.130667 76.266667-270.432 188.693334-2.730667 7.445333-7.402667 20.32-13.994667 38.581333-7.68 21.301333-34.453333 28.106667-51.370666 13.056-16.437333-14.634667-28.554667-25.066667-36.138667-31.146667A222.890667 222.890667 0 0 0 192 661.333333c-14.464 0-28.725333 1.365333-42.666667 4.053334V768a53.333333 53.333333 0 0 0 53.333334 53.333333h618.666666a53.333333 53.333333 0 0 0 53.333334-53.333333V561.525333zM320 480a96 96 0 1 1 0-192 96 96 0 0 1 0 192z m0-64a32 32 0 1 0 0-64 32 32 0 0 0 0 64z" fill="#9499a0" p-id="6392"></path></svg>
          </div>
          <el-popover
          placement="top-start"
          :width="350"
          :offset="5"
          trigger="click"
          :show-arrow="false"
          transition="none"
          :popper-style="{
          borderRadius: '8px',
          boxShadow: 'none',
          padding:'0'
          }">
            <template #reference>
            <div class="_MessageSendBox__ToolBtn_1izxa_13" >
            <svg t="1755136377928" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8345" width="21" height="21"><path d="M512 0C229.2 0 0 229.2 0 512s229.2 512 512 512 512-229.2 512-512S794.8 0 512 0z m0 960C265 960 64 759 64 512S265 64 512 64s448 201 448 448-201 448-448 448z" p-id="8346" fill="#9499a0"></path><path d="M320 405.3m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="8347" fill="#9499a0"></path><path d="M704 405.3m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="8348" fill="#9499a0"></path><path d="M512 810.7c117.8 0 213.3-95.5 213.3-213.3H298.7c0 117.8 95.5 213.3 213.3 213.3z" p-id="8349" fill="#9499a0"></path></svg>
            </div>
            </template>
            <Emoticons/>
          </el-popover>
        </div>
        <!-- 内容输入 -->
        <div class="_MessageSendBox__Textarea_1izxa_42 msb-textarea">
          <el-input
          v-model="textarea"
          :rows="3"
          type="textarea"
          maxlength="500"
          placeholder="请输入消息内容"
          class="input-textarea"
          @keydown.enter.exact.prevent="onSend"
        />  
        </div>
        <!-- 发送区域 -->
         <div class="_MessageSendBox__Send_1izxa_60">
          <div class="_MessageSendBox__Indicator_1izxa_91">
            <span class="_MessageSendBox__IndicatorValue_1izxa_96">{{textarea.length}}</span>
            <span>/500</span>
          </div>
          <div ref="sendBtnEl" 
          :class="[textarea.length === 0 ? '_IsDisabled_1izxa_22' : '_MessageSendBox__SendBtn_1izxa_69']"
          @click="onSend">发送</div>
         </div>
      </div>
     </div>
</div>
          

</template>
<script setup>
import Emoticons from '@/components/Emoticons.vue';
import {  onMounted, ref, nextTick,onUnmounted } from 'vue'
import { useUserStore } from '@/store/useUserStore';
import { getPersonList ,getMessageList} from '@/api/myMessage';
import { storeToRefs } from 'pinia';
import emitter from '@/utils/eventBus';
import {remarkRead} from '@/api/myMessage';
import { useMessageStore } from '@/store/useMessageStore';


const userStore = useUserStore();
const messageStore = useMessageStore();
const {userInfo}=storeToRefs(userStore);
const chatContentEl = ref(false);//点击聊天框
const textarea = ref('')
const uploaderPic = ref(null);//图片上传按钮引用
const sendBtnEl = ref(null);//发送按钮状态
const personList = ref([]);//消息列表
const currentChatPerson = ref(null);//当前聊天对象
const messageList = ref([]);//消息列表
const chatScrollbar = ref(null); // 聊天滚动容器
const emit=defineEmits(['sendMessage'])


//发送消息
function onSend(){
  if (!currentChatPerson.value) return
  //排除空消息
  const content = (textarea.value || '').trim()
  if (!content) return
  //发送给服务端
  const sendPayload = {
    toUserId: currentChatPerson.value.userId,
    message: content,
  }
  try {
    //发送消息
    emit('sendMessage',sendPayload)
  } catch (e) {
    console.log('发送失败:', e)
  } 
  //本地乐观更新
  const localMsg = {
    senderId: userInfo.value.userId,
    receiverId: currentChatPerson.value.userId,
    content: content,
    sendTime: new Date(),
  }
  messageList.value.push(localMsg)
  //将发送的消息内容置为列表人的记录显示的最后一条消息
  personList.value.find((item) => item.userId === currentChatPerson.value.userId).lastMessage = content
  textarea.value = ''
  scrollToBottom()
}

//接收消息
function handleReciveMessage(data){
  if(!data) return
  //解析消息格式
  const message={
    senderId:Number(data.fromUserId),//这里的data.fromUserId是String类型
    receiverId: userInfo.value.userId,
    content: data.message,
    sendTime: new Date(),
  }
  //如果消息是当前聊天对象
  if (currentChatPerson.value && message.senderId=== currentChatPerson.value?.userId) {
    messageList.value.push(message)
    scrollToBottom()
    remarkReadFuc()//调后端接口标记redis中已读（可优化）
    messageStore.decreMyMessageCount() //我在父组件分发消息时未读数+1，子组件接收这里的是当前窗口未读数-1
  }
  else{
  //如果不是当前窗口口就定位发送人的未读数+1
    addUnread(message.senderId,message.content)    
  }
}


//定位发送人的消息未读数+1
function addUnread(userId,content){
  const person = personList.value.find((item) => item.userId === userId)
  if (!person) return
  person.unreadCount = person.unreadCount + 1
  person.lastMessage =content
}

//未读数跟新到pinia中
function updateUnreadCount(){
  const sum=personList.value.reduce((sum,curr)=>{
    return sum+curr.unreadCount
  },0)
  messageStore.setMyMessageCount(sum)
}

//获取消息列表
async function getPersonListFuc(){
  if(!userInfo.value.userId) return
  try{
    const res=await getPersonList(userInfo.value.userId)
    personList.value=res
    updateUnreadCount()
  }catch (error) {
    console.log(error)
  }
}

//聊天内容滚动到最底部
function scrollToBottom(){
  nextTick(() => {
    const wrap = chatScrollbar.value?.wrapRef
    if (wrap) wrap.scrollTop = wrap.scrollHeight
  })
}

//获取聊天消息
async function getMessageListFuc(){
  if(!userInfo.value.userId){
    return
  }
  try{
    const params={
      myId:userInfo.value.userId,
      toId:currentChatPerson.value.userId
    }
    const res=await getMessageList(params)
    //根据时间对消息排序
    const sorted = (Array.isArray(res) ? res : []).slice().sort((a,b)=>{
      return toTimestamp(a.sendTime) - toTimestamp(b.sendTime)
    })
    messageList.value = sorted
    scrollToBottom()
  }catch (error) {
    console.log(error)
  }
}

//进入聊天对话框
function enterChat(item){
    currentChatPerson.value = item
    chatContentEl.value = true
    getMessageListFuc()  //获取聊天消息
    item.unreadCount=0  //将未读数清零
    updateUnreadCount()
    remarkReadFuc() //调后端接口标记redis中已读（可优化）
}

//标记消息为已读
async function remarkReadFuc(){
  if(!userInfo.value.userId){
    return
  }
  try{
    const params={
      receiverId:userInfo.value.userId,
      senderId:currentChatPerson.value.userId
    }
    const res=await remarkRead(params)
  }catch (error) {
    console.log(error)
  }
}

//转化成时间戳
function toTimestamp(value){
  if(!value) return 0
  if (typeof value === 'string') {
    return new Date(value.replace(/-/g, '/')).getTime()
  }
  try {
    return new Date(value).getTime()
  } catch (e) {
    return 0
  }
}

// 是否需要显示该条消息的时间
function shouldShowTime(index){
  if (index === 0) return true
  const prev = messageList.value[index - 1]  //上一条消息 
  const curr = messageList.value[index] //该条消息
  const diff = Math.abs(toTimestamp(curr?.sendTime) - toTimestamp(prev?.sendTime))
  return diff >= 5 * 60 * 1000
}


//处理显示的消息时间格式
function handleTime(time){
  if(!time) return ''
  let date
  if (typeof time === 'string') {
    date = new Date(time.replace(/-/g, '/'))
  } else {
    date = new Date(time)
  }
  if (isNaN(date.getTime())) return ''
  const yyyy = date.getFullYear()
  const MM = (date.getMonth() + 1).toString().padStart(2, '0')
  const dd = date.getDate().toString().padStart(2, '0')
  const HH = date.getHours().toString().padStart(2, '0')
  const mm = date.getMinutes().toString().padStart(2, '0')
  return `${yyyy}年${MM}月${dd}日 ${HH}:${mm}`
}

//上传图片
function handleChooseImage(){
  console.log('上传图片事件触发')
  uploaderPic.value.click();
  //直接发送
}


onMounted(()=>{
  getPersonListFuc()
  emitter.on('chatMessage',handleReciveMessage)
})
onUnmounted(()=>{
  emitter.off('chatMessage',handleReciveMessage)
})
</script>
<style scoped>
.message-box-shadow {
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 2px 4px 0 rgba(121, 146, 185, 0.54);
}
.message-content__wrapper{
  display: flex;
  box-sizing: border-box;
  width: 100%;
  height: 82vh;
}
._Sidebar_1k2p2_10{
  height: 100%;
  width: 240px;
  box-sizing: border-box;
  border-right: 1px solid #E3E5E7;
  font-family: Microsoft YaHei;
  display: flex;
  flex-direction: column;

}
._SidebarHeader_1k2p2_17 {
  padding: 0 24px;
  height: 36px;
  box-sizing: border-box;
  border-bottom: 1px solid #E3E5E7;
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #61666d;
}
._SidebarTitle_1k2p2_28 {
    line-height: 1;
}
.scroll-container{
  flex:1;
  overflow: hidden; 
}
._SessionItem_dnmx0_1 {
  width: 100%;
  padding: 19px 12px 19px 24px;
  position: relative;
  display: flex;
  cursor: pointer;
  box-sizing: border-box;
}
._SessionItem_dnmx0_1:hover, ._SessionItemIsActive_dnmx0_12 {
    background-color: #f1f2f3;
}
._SessionItem__Avatar_dnmx0_21 {
  display: flex;
  gap: 5px;
  position: relative;
  width: 100%;
  margin-right: 8px;
  flex-shrink: 0;
 
}
.bili-avatar__layer {
    position: absolute;
    isolation: isolate;
   
}
.bili-avatar * {
    margin: 0;
    padding: 0;
}
.bili-avatar__layer__res.local-4 {
    background-image: url("/public/emo/image.png");
}
.bili-avatar__layer__res {
    width: 100%;
    height: 100%;
    isolation: isolate;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    position: relative;
    border: 1px solid #fff;
    border-radius: 50%;
    top:-5px;
    right: 7px;

}
._SessionItem__Main_dnmx0_42 {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;

}
._SessionItem__Tag_dnmx0_53, ._SessionItem__Title_dnmx0_49 {
    display: flex;
    align-items: center;
}
._SessionItem__Info_dnmx0_97 {
    display: flex;
    align-items: center;
    font-size: 12px;
    line-height: 18px;
    font-family: fMicrosoft YaHei;
}
._SessionItem__Message_dnmx0_107 {
    flex: 1;
    overflow: hidden;
    color: #9499A0;
    text-overflow: ellipsis;
    white-space: nowrap;
}

._SessionItem__Notification_dnmx0_114 {
    position: absolute;
    top: 5px;
    right: 8px;
}
._SessionItem__NotificationNumber_dnmx0_124 {
    background-color: #f69;
    color: #fff;
    box-sizing: border-box;
    min-width: 16px;
    height: 16px;
    line-height: 16px;
    padding: 0 4px;
    text-align: center;
    font-size: 12px;
    border-radius: 8px;
}

._Main_1k2p2_60 {
  width: calc(100% - 240px);
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: #f6F7F8;
  
}
._ChatWindow_1lacc_1 {
    width: 100%;
    height: 100%;
    background-color: #f6f7f8;
    position: relative;
    display: flex;
    flex-direction: column;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    /* border: 1px solid red; */
}
._ChatWindowIsActive_1lacc_11 {
    z-index: 2;
}
._ChatPlaceholder_1lacc_95 {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
   
    
}
._ChatPlaceholder_1lacc_95 img {
    width: 402px;
    height: 204px;
    margin-bottom: 32px;
}
._ChatPlaceholder_1lacc_95 p {
    margin: 0;
    color: #8d9fb9;
    font-size: 14px;
    line-height: 1.5em;
}
p {
    display: block;
    margin-block-start: 1em;
    margin-block-end: 1em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    unicode-bidi: isolate;
}
._ChatHeader_1lacc_14 {
  width: 100%;
  height: 36px;
  box-sizing: border-box;
  flex-shrink: 0;
  border-bottom: 1px solid #E3E5E7;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;

}
._ContactName_1lacc_26 {
  font-size: 14px;
  color: #18191C;
}
._ContactSettings_1lacc_30 {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    color: #9499A0;
}
._MoreAction_1lacc_39 {
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}
._ChatContent_1lacc_58 {
    width: 100%;
    height: 68%;
    overflow: hidden;
    /* border: 1px solid green; */
}
._InfiniteScroll_wmrzv_1 {
    width: 100%;
    height: 100%;
    position: relative;
    /* border: 1px solid green; */
}

/* 时间分割样式 */
.time-divider {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px 0;
}
.time-divider .label {
    font-size: 12px;
    padding: 2px 8px;
    text-align: center;
    color: #61666d;
}


/* 聊天消息样式 */
.chat-message {
    display: flex;
    align-items: flex-end;
    gap: 8px;
    padding: 8px 16px;
}
.chat-message.from-them {
    justify-content: flex-start;
}
.chat-message.from-me {
    justify-content: flex-end;
}
.chat-message .avatar {
    flex-shrink: 0;
}
.chat-message .bubble {
    max-width: 60%;
    padding: 8px 10px;
    border-radius: 8px;
    background-color: #fff;
    color: #18191C;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.chat-message.from-me .bubble {
    background-color: #00aeec;
    color: #fff;
}
.chat-message .bubble .content {
    white-space: pre-wrap;
    word-break: break-word;
}
 


._ChatFooter_1lacc_89 {
    width: 100%;
    flex-shrink: 0;
    height: 20%;
    border-top: 1px solid #E3E5E7;
    /* border: 1px solid aqua; */
}
._MessageSendBox__Toolbar_1izxa_6 {
    position: relative;
    height: 48px;
    display: flex;
    padding: 12px 16px;
    box-sizing: border-box;
}
._MessageSendBox__ToolBtn_1izxa_13 {
    position: relative;
    width: 24px;
    height: 24px;
    margin-right: 16px;
    cursor: pointer;
    padding: auto;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: center;}

._MessageSendBox__Textarea_1izxa_42 {
    box-sizing: border-box;
    width: 100%;
    height: 50%;
    background-color: transparent;
    color: #18191C;
    padding: 0 10px;
    /* border: 1px solid rebeccapurple; */
}
._MessageSendBox__Textarea_1izxa_42 .input-textarea{
  width: 100%;
  height: 100%;
  border: none;
  background-color: transparent;

}
._MessageSendBox__Textarea_1izxa_42 .input-textarea:focus{
  outline: none;
}
.input-textarea :deep(.el-textarea__inner) {
  border: none;
  outline: none;
  background: transparent;
  height: 70px;
  resize: none; 
  box-shadow: none;
}
._MessageSendBox__Send_1izxa_60 {
    width: 100%;
    height: 46px;
    padding: 0 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    /* border: 1px solid red; */
}
._MessageSendBox__Indicator_1izxa_91 {
    color: #9499A0;
    font-size: 12px;
    margin-right: 12px;
}
._IsDisabled_1izxa_22 {
    background-color: #fff;
    color: #18191C;
    cursor: not-allowed;
    width: 88px;
    font-size: 13px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 4px;
    border: 1px solid #E3E5E7;
    transition: 0.2s;    
}
._MessageSendBox__SendBtn_1izxa_69 {
    width: 88px;
    font-size: 13px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 4px;
    background-color: #00aeec;
    border-color: #00aeec;
    border: 1px solid #00aeec;
    color: #fff;
    cursor: pointer;
    transition: 0.2s;
}
@media screen and (min-width: 1920px) {
  .message-content__wrapper{
  height: 86vh;
}

  
}
</style>